package cc.ok200.muzhi;

import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

// 插件市场
public class MarketActivity extends AppCompatActivity {
    
    private static final String TAG = "MarketActivity";
    private RecyclerView rvMarketPlugins;
    private MarketPluginAdapter marketPluginAdapter;
    private JSONArray marketPluginsArray = new JSONArray();
    private JSONArray filteredPluginsArray = new JSONArray();
    private EditText etSearch;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 设置沉浸式状态栏
        setImmersiveStatusBar();
        
        setContentView(R.layout.activity_market);
        
        // 初始化UI
        initUI();
        
        // 加载插件数据
        loadMarketPluginsFromJson();
        
        // 设置适配器
        setupMarketRecyclerView();
        
        // 设置搜索功能
        setupSearchFunction();
    }
    
    private void initUI() {
        // 设置工具栏
        Toolbar toolbar = findViewById(R.id.toolbar_market);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        
        TextView toolbarTitle = findViewById(R.id.toolbar_market_title);
        toolbarTitle.setText("插件市场");
        
        // 设置返回按钮
        ImageButton btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> onBackPressed());
        
        // 获取搜索框引用
        etSearch = findViewById(R.id.et_search);
        
        // 获取RecyclerView引用
        rvMarketPlugins = findViewById(R.id.rv_market_plugins);
    }
    
    private void setupSearchFunction() {
        // 设置搜索框文本变化监听
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要实现
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 过滤插件列表
                filterPlugins(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 不需要实现
            }
        });
        
        // 设置搜索动作监听
        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // 执行搜索
                filterPlugins(etSearch.getText().toString());
                return true;
            }
            return false;
        });
    }
    
    private void filterPlugins(String query) {
        try {
            // 如果搜索词为空，显示全部插件
            if (query == null || query.trim().isEmpty()) {
                filteredPluginsArray = new JSONArray();
                for (int i = 0; i < marketPluginsArray.length(); i++) {
                    filteredPluginsArray.put(marketPluginsArray.getJSONObject(i));
                }
                marketPluginAdapter = new MarketPluginAdapter(this, filteredPluginsArray);
                setupAdapterListeners();
                rvMarketPlugins.setAdapter(marketPluginAdapter);
                return;
            }
            
            // 转为小写以便不区分大小写比较
            String lowercaseQuery = query.toLowerCase();
            
            // 创建新的JSONArray用于存储过滤后的结果
            filteredPluginsArray = new JSONArray();
            
            // 遍历所有插件进行过滤
            for (int i = 0; i < marketPluginsArray.length(); i++) {
                JSONObject plugin = marketPluginsArray.getJSONObject(i);
                String name = plugin.getString("name").toLowerCase();
                String type = plugin.getString("type").toLowerCase();
                String desc = plugin.getString("description").toLowerCase();
                String author = plugin.getString("author").toLowerCase();
                
                // 如果任一字段包含搜索词，则加入过滤结果
                if (name.contains(lowercaseQuery) || 
                    type.contains(lowercaseQuery) || 
                    desc.contains(lowercaseQuery) || 
                    author.contains(lowercaseQuery)) {
                    filteredPluginsArray.put(plugin);
                }
            }
            
            // 更新适配器数据
            marketPluginAdapter = new MarketPluginAdapter(this, filteredPluginsArray);
            setupAdapterListeners();
            rvMarketPlugins.setAdapter(marketPluginAdapter);
            
        } catch (JSONException e) {
            Log.e(TAG, "过滤插件时出错: " + e.getMessage());
        }
    }
    
    private void loadMarketPluginsFromJson() {
        try {
            // 从assets目录读取插件配置文件
            String jsonString = readAssetFile("market_plugins.json");
            
            // 解析JSON数组
            marketPluginsArray = new JSONArray(jsonString);
            
            // 初始化过滤后的数组
            filteredPluginsArray = new JSONArray();
            for (int i = 0; i < marketPluginsArray.length(); i++) {
                filteredPluginsArray.put(marketPluginsArray.getJSONObject(i));
            }
            
        } catch (JSONException e) {
            Log.e(TAG, "JSON解析错误: " + e.getMessage());
            Toast.makeText(this, "加载市场插件数据失败", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Log.e(TAG, "读取文件错误: " + e.getMessage());
            Toast.makeText(this, "读取市场插件配置文件失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private String readAssetFile(String fileName) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        
        try (InputStream is = getAssets().open(fileName);
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        
        return stringBuilder.toString();
    }
    
    private void setupMarketRecyclerView() {
        rvMarketPlugins.setLayoutManager(new LinearLayoutManager(this));
        
        marketPluginAdapter = new MarketPluginAdapter(this, filteredPluginsArray);
        setupAdapterListeners();
        rvMarketPlugins.setAdapter(marketPluginAdapter);
    }
    
    private void setupAdapterListeners() {
        // 设置点击监听器
        marketPluginAdapter.setOnItemClickListener((position, pluginObject) -> {
            try {
                String pluginName = pluginObject.getString("name");
                String pluginPrice = pluginObject.getString("price");
                
                Toast.makeText(this, pluginName + " - " + pluginPrice, Toast.LENGTH_SHORT).show();
                
                // 在这里可以实现查看详情功能
            } catch (JSONException e) {
                Log.e(TAG, "JSON解析错误: " + e.getMessage());
            }
        });
        
        // 设置下载按钮点击监听器
        marketPluginAdapter.setOnDownloadClickListener((position, pluginObject) -> {
            try {
                String pluginName = pluginObject.getString("name");
                String pluginPrice = pluginObject.getString("price");
                
                if (pluginPrice.equals("免费")) {
                    Toast.makeText(this, "开始下载: " + pluginName, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "需要付费: " + pluginPrice, Toast.LENGTH_SHORT).show();
                }
                
                // 在这里可以实现下载或购买逻辑
            } catch (JSONException e) {
                Log.e(TAG, "JSON解析错误: " + e.getMessage());
            }
        });
    }
    
    /**
     * 设置沉浸式状态栏，使状态栏颜色与应用主题色一致
     */
    private void setImmersiveStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            // 设置状态栏绘制模式
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            // 状态栏透明
            window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
            
            // 布局内容扩展到状态栏
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            
            // 对于Android 6.0及以上版本，可以设置状态栏文字颜色
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 如果主题色较深，状态栏文字使用白色
                // 如果需要黑色文字，则添加 View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                window.getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            }
        }
    }
} 